<?php
	// Returns the number of rows in a single dimension array that aren't empty
	function getOccupiedRowCount($attr)
	{
		$result = 0;
		for($i = 0; $i<count($attr);$i++)
		{
			if(!empty($attr[$i]))
				$result++;
		}
		return $result;
	}
	
	/* FUNCTION : isValidCollection($colName, $arrColAttributes, $isCreate)
	 * IN:
	 * colName: (String) contains the collection name being created/edited
	 * arrColAttributes: (String[]) array of attribute names
	 * isCreate: (bool) true - create collection,  false - edit collection
	 *
	 * OUT:
	 * (int) 1 - Clear for takeoff
	 *      -1 - Invalid collection name
	 *      -2 - Invalid attribute name
	 *      -3 - Duplicate attribute name
	 *		-4 - No attributes.
	 *
	 * Validation Process for when a collection is created
	 * 1. Make sure the collection name is valid and not a duplicate
	 * 2. Make sure that there isn't an attribute with the same name
	 * 3. Make sure at least one attribute has been filled in.
	 */
	function checkValidCollection($colName, $arrColAttributes, $isCreate)
	{
		$filledInAttribute = 0;
		
		/* Applys the following checks
		 * 1. Validate characters in collection name
		 * 2. Validate it is not a duplicate name */
		if($isCreate && !validateCollectionName($colName))
		{
			return -1;
		}
		// Validate no attribute is the same
		$arrSize = count($arrColAttributes);	
		for($outer = 0; $outer < $arrSize; $outer++)
		{
			// If attribute is empty just continue on
			if(!empty($arrColAttributes[$outer]))
			{
				// Increment attribute count
				$filledInAttribute++;
				
				// Check is valid format for attribute
				if(!validateAttributes($arrColAttributes[$outer]))
				{
					return -2;
				}
				
				for($inner = $outer+1; $inner < $arrSize; $inner++)
				{
					// If two attributes are the same throw error.
					if(strcasecmp($arrColAttributes[$outer],$arrColAttributes[$inner]) == 0)
					{
						return -3;
					}
				}
			}
		}
		
		// Throw error is at least one attribute hasn't been filled in.
		if($filledInAttribute == 0)
		{
			return -4;
		}

		return 1; // As in, happy as two clams on the beach drinking a corona.
	}
	/* Function used to remove user name from the beginning of passed colname 
	 */
	function removeUID($strCollectName)
	{
		$userName = (string)$_SESSION['user_name'];
		return substr($strCollectName, strlen($userName)+1);
	}
	/* Function used to get the user name of a collection - assists in validation
	 */
	function getUID($strCollectName)
	{
		$query = 
			"SELECT collection_user_id FROM collection WHERE collection_name = '"
			. mysql_real_escape_string($strCollectName)
			. "';";
		if(!$result = mysql_query($query))
			die("Error");
		$arrayResult = mysql_fetch_array($result);
		return $arrayResult[0];
	}
	/* Returns list of fields to be outputted from attributes table
	 * with commas between.
	 */
	function getProjection($colName, $userName)
	{
		// Query to get column names of collection
		$columnNameQuery = "SELECT attribute_name FROM attribute A"
						 . " WHERE A.attribute_collection_name = '"
						 . mysql_real_escape_string($colName)
						 . "' AND A.attribute_user_id ='"
						 . mysql_real_escape_string($userName)
						 . "' ORDER BY A.attribute_id;";
		
		//Query for grabbing column names
		if(!$columnNamesResult = mysql_query($columnNameQuery))
		{
			echo $columnNameQuery;
			die("Error");
		}
		// Gathor all the attribute names
		for($i=0;  ($i+1) < mysql_num_rows($columnNamesResult); $i++)
		{ 
				$row = mysql_fetch_row($columnNamesResult);
				$projection = $projection . $row[0] . ", ";
		}
		$row = mysql_fetch_row($columnNamesResult);
		$projection = $projection . $row[0];
		return $projection;
	}
	// Validate username based off legal characters
	function validateUsername($in)
	{
		if(!preg_match("/^[A-Za-z0-9_]+$/",$in))
			return false;
		if(!preg_match("/[A-Za-z]+/",$in))
			return false;
			
		return true;
	}

	// Validate email address based off legal format
	function validateEmailAddress($in)
	{
		if(!preg_match("/.+@.+\..+/",$in))
			return false;
		return true;
	}
	
	// Validate attributes based off legal characters
	function validateAttributes($in)
	{
		if(!preg_match("/^[A-Za-z0-9_]+$/",$in))
			return false;
		if(!preg_match("/[A-Za-z]+/",$in))
			return false;
			
		return true;
	}

	// Validate input for collection name
	function validateCollectionName($in)
	{
		if(!preg_match("/^[A-Za-z0-9_]+$/",$in))
			return false;
		//Make sure collection name is not already used
		$cNameQuery = 
			"SELECT * FROM collection WHERE collection_user_id = '"
			. mysql_real_escape_string($_SESSION['user_name'])
			. "' AND collection_name = '"
			. mysql_real_escape_string($_SESSION['user_name'] . "_" . $in)
			. "';";
		if(!$queryResult = mysql_query($cNameQuery))
			die($cNameQuery);
		if(mysql_num_rows($queryResult) >= 1)
			return false;
		return true;
	}
	
	// Return true if strType contains the string VARCHAR
	function isVarChar($strTypeText)
	{
		if(stripos($strTypeText, "VARCHAR") === false)
			return false;
		return true;
	}
	
	// Return true if strType contains the string INTEGER
	function isInteger($strTypeText)
	{
		if(stripos($strTypeText, "INTEGER") === false)
			return false;
		return true;
	}
	
	// Return true if strType contains the string REAL
	function isReal($strTypeText)
	{
		if(stripos($strTypeText, "REAL") === false)
			return false;
		return true;
	}
	
	//Checks $str to see if it matches the requirements for a URL
	//Regex used from here: http://snippets.dzone.com/posts/show/452
	function isUrl($str)
	{
		if(preg_match("/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/", $str))
			return true;
		return false;
	}
	
	//Populate the rating spinner with the rating of the collection/item being edited
	function selectRating($r)
	{
		switch($r)
		{
			case 1:	
				echo 	"<option value=\"zero\">0</option>";
				echo 	"<option value=\"one\" selected=\"selected\">1</option>";
				echo 	"<option value=\"two\">2</option>";
				echo	"<option value=\"thr\">3</option>";
				echo	"<option value=\"four\">4</option>";
				echo	"<option value=\"five\">5</option>";
				break;
			case 2:	
				echo	"<option value=\"zero\">0</option>";
				echo 	"<option value=\"one\">1</option>";
				echo 	"<option value=\"two\" selected=\"selected\">2</option>";
				echo	"<option value=\"thr\">3</option>";
				echo	"<option value=\"four\">4</option>";
				echo	"<option value=\"five\">5</option>";
				break;
			case 3:	
				echo	"<option value=\"zero\">0</option>";
				echo 	"<option value=\"one\">1</option>";
				echo 	"<option value=\"two\">2</option>";
				echo	"<option value=\"thr\" selected=\"selected\">3</option>";
				echo	"<option value=\"four\">4</option>";
				echo	"<option value=\"five\">5</option>";
				break;
			case 4:
				echo	"<option value=\"zero\">0</option>";
				echo 	"<option value=\"one\">1</option>";
				echo 	"<option value=\"two\">2</option>";
				echo	"<option value=\"thr\">3</option>";
				echo	"<option value=\"four\" selected=\"selected\">4</option>";
				echo	"<option value=\"five\">5</option>";
				break;
			case 5:
				echo 	"<option value=\"zero\">0</option>";
				echo 	"<option value=\"one\">1</option>";
				echo 	"<option value=\"two\">2</option>";
				echo	"<option value=\"thr\">3</option>";
				echo	"<option value=\"four\">4</option>";
				echo	"<option value=\"five\" selected=\"selected\">5</option>";
				break;
			default:
				echo 	"<option value=\"zero\" selected=\"selected\">0</option>";
				echo 	"<option value=\"one\">1</option>";
				echo 	"<option value=\"two\">2</option>";
				echo	"<option value=\"thr\">3</option>";
				echo	"<option value=\"four\">4</option>";
				echo	"<option value=\"five\">5</option>";
				break;
		}
	}
	
	//Populate the type spinner with the type of the attribute in the collection
	function selectAttributeType($t)
	{
		switch($t)
		{
			case 'INTEGER':
				echo "<option value=\"str\">String</option>";
				echo "<option value=\"int\" selected=\"selected\">Number (Integer)</option>";
				echo "<option value=\"dbl\">Number (Decimal)</option>";
				break;
			case 'REAL':
				echo "<option value=\"str\">String</option>";
				echo "<option value=\"int\">Number (Integer)</option>";
				echo "<option value=\"dbl\" selected=\"selected\">Number (Decimal)</option>";
				break;
			default:
				echo "<option value=\"str\" selected=\"selected\">String</option>";
				echo "<option value=\"int\">Number (Integer)</option>";
				echo "<option value=\"dbl\">Number (Decimal)</option>";
				break;
		}
	}
	
	/**
	 * Get a string according to what attribute type is passed in
	 */
	function selectAttributeTypeString($t)
	{
		switch($t)
		{
			case 'INTEGER':
				return "Integer";
				break;
			case 'REAL':
				return "Real";
				break;
			default:
				return "String";
				break;
		}
	}
	
	/**
	 * Function gets all attributes and their types from a specified collection
	 */
	function getAttributes($cname)
	{
		// Query to get column names of collection
		$attributesQuery = 
			"SELECT A.attribute_name, A.attribute_type FROM attribute A"
			 . " WHERE A.attribute_collection_name = '"
			 . mysql_real_escape_string($cname)
			 . "' AND A.attribute_user_id ='"
			 . mysql_real_escape_string($_SESSION['user_name'])
			 . "' ORDER BY A.attribute_id;";
		if($retVal = mysql_query($attributesQuery))	 
			return $retVal;
		else
			die("Unable to retrieve attributes");
	}
	
	/**
	 * Gets the specified collection's description
	 */
	function getDescription($cname)
	{
		$description =
			mysql_fetch_array(
				mysql_query(
					"SELECT collection_desc FROM collection WHERE collection_name = '"
					. mysql_real_escape_string($cname)
					. "' AND collection_user_id = '"
					. mysql_real_escape_string($_SESSION['user_name'])
					. "';"
				)
			);
		if($description)	 
			return (string)$description[0];
		else
			die("Unable to retrieve description");
	}
	
	/**
	 * Gets the specified collection's rating
	 */
	function getRating($cname)
	{
		$rating =
			mysql_fetch_array(
				mysql_query(
					"SELECT collection_rating FROM collection WHERE collection_name = '"
					. mysql_real_escape_string($cname)
					. "' AND collection_user_id = '"
					. mysql_real_escape_string($_SESSION['user_name'])
					. "';"
				)
			);
		if($rating)	 
			return (int)$rating[0];
		else
			die("Unable to retrieve rating");
	}
	/*Returns the SQL version of int, real, and string*/
	function findType($typeAbbr)
	{
		switch((string)$typeAbbr)
		{
			case "int": return "INTEGER"; break;
			case "dbl": return "REAL"; break;
			default: return "VARCHAR(128)"; break;
		}
	}
	/*Checks to see if input is an integer*/
	function isIntegerData($in)
	{
		if(!preg_match("/^-?[0-9]{1,}$/",$in))
			return false;
		return true;
	}
	/*Checks to see if input is a real value*/
	function isRealData($in)
	{
		if(!preg_match("/^-?[0-9]{1,}\.?[0-9]{1,}?$/",$in))
			return false;
		return true;
	}
	
	/*Cleans up item table if error after initial query*/
	function removeItem($id)
	{
		$removal = 
			"DELETE FROM item WHERE item_id = " 
			. mysql_real_escape_string($id) 
			. " AND item_user_id = '"
			. mysql_real_escape_string($_SESSION['user_name'])
			. "';";
		
		if(!$removeResult = mysql_query($removal))
		{
			echo $removal;
			die(": Houston, we have a problem.");
		}
	}
?>